package com.guokeai.session;

import com.guokeai.pojo.Person;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

/**
 * @author
 * @create 2021-04-27 20:03
 */
public class Session01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html；charset=utf-8");

        //得到session
        HttpSession session = req.getSession();
        //给session中存入东西
        //session.setAttribute("name","王可爱");
        session.setAttribute("name",new Person("王可爱",3));

        String sessionId = session.getId();
        if (session.isNew()){
            resp.getWriter().write("session创建成功，id为：" + sessionId);
        }else{
            resp.getWriter().write("session已存在，id为：" + sessionId);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
